package com.wang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class ServletFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //对inner中的bar进行过滤,登录获取session才能观看
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取url进行判断有没有login的和adduser的有则无条件放行,
        String uri = request.getRequestURI();
        if(uri.indexOf("login")!=-1||uri.indexOf("adduser")!=-1||"/".equals(uri)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //如果是访问其他的uri则需要session
        HttpSession session = request.getSession(false);
        if(session != null){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        request.getRequestDispatcher("/login_error").forward(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
